<?php

/**
 * 资讯类
 */
class bbsModel
{


    public function __construct(& $base)
    {
        $this->base = $base;
        $this->db = & $this->base->db;
        $this->redis = & $this->base->redis;
    }
    /*
     * 获取版块列表
     * @return $array
    */
    public function getBoardList($isAll = true)
    {
        $result = array();
        $start = $isAll ? '-inf': 1;
        $boardList = $this->redis->ZRANGEBYSCORE(REDIS_PREFIX.'BoardList', $start, '+inf');
        if(empty($boardList))
        {
            $boardData = $this->db->getAll("select boardId, sortOrder from r_board");
            foreach ($boardData as $v) {
                $this->redis->ZADD(REDIS_PREFIX.'BoardList', $v['sortOrder'], $v['boardId']);
            }
            $boardList = $this->redis->ZRANGEBYSCORE(REDIS_PREFIX.'BoardList', $start, '+inf');
        }
        if($boardList)
        {
            foreach ($boardList as $boardId) {
                $info = $this->getBoardInfo($boardId);
                if(!empty($info))
                {
                    unset($info['boardDesc'],$info['sortOrder'],$info['totalPost']);
                    $result[] = $info;
                }
                unset($info);
            }
        }
        return $result;
    }
    /*
     * 添加或添加版块
     * array $boardInfo
     * @return $array
    */
    public function updateBoard($boardInfo = array())
    {
        $result = false;
        if(!empty($boardInfo) && isset($boardInfo['boardId']))
        {
            $result = $this->db->updateRowTable('r_board',$boardInfo);
            if($result)
            {
                isset($boardInfo['sortOrder']) && $this->redis->ZADD(REDIS_PREFIX.'BoardList', $boardInfo['sortOrder'], $boardInfo['boardId']);
                $this->redis->hmset(REDIS_PREFIX.'BoardInfo_'.$boardInfo['boardId'], $boardInfo);
            }
        }
        return $result;
    }
    /*
     * 获取版块信息
     * int $boardId 版块ID
     * @return $array
    */
    public function getBoardInfo($boardId)
    {
        $result = $this->redis->hgetall(REDIS_PREFIX.'BoardInfo_'.$boardId);
        if(empty($result))
        {
            $result = $this->db->getRowTable('r_board', array(), "boardId = '{$boardId}'");
            if(!empty($result))
            {
                $result['boardImg'] == '' && $result['boardImg'] = 'http://'.$this->base->config['host'].'/static/backend/boardImg/'.$result['boardId'].'.png';
                $result['totalPost'] = $this->redis->ZCARD(REDIS_PREFIX.'BoardPostList'.$boardId.'_New').'';
                unset($result['id']);
                $this->redis->hmset(REDIS_PREFIX.'BoardInfo_'.$boardId, $result);
            }
        }
        !empty($result) && $result['totalPost'] = $this->redis->ZCARD(REDIS_PREFIX.'BoardPostList'.$boardId.'_New').'';
        return $result == false ? array() : $result;
    }
    /*
     * 获取焦点图
    */
    public function getFocusPic()
    {
        return $this->base->load('banner')->getBbsFocusPic();
    }
    /*
     * 获取每日最In的帖子
     * @return $array
    */
    public function getDailyShow()
    {
        $result = $this->redis->get(REDIS_PREFIX.'DailyShow');
        if($result)
        {
            $result = json_decode($result, true);
        }
        $result = is_array($result) ? $result : array();
        return $result;
    }
    /*
     * 获取社区首页热门话题
     * @return $array
    */
    public function getTopHotPost($limit = 10)
    {
        $result = array();
        $limit = intval($limit);
        $postIds = $this->redis->ZREVRANGEBYSCORE(REDIS_PREFIX.'TopHotpost', '+inf', '-inf', array('limit' => array(0,$limit)));
        if(empty($postIds)){
            $this->updateTopHotPost();
            $postIds = $this->redis->ZREVRANGEBYSCORE(REDIS_PREFIX.'TopHotpost', '+inf', '-inf', array('limit' => array(0,$limit)));
        }
        empty($postIds) && $postIds = array();
        return $postIds;
    }
    /*
     * 获取版块下帖子列表
     * @return $array
    */
    public function getBoardPostList($boardId, $listType=0, $news_id=0, $direc ='next', $offset = 10)
    {
        $result = array();
        $postListType = common::$postListType;
        $type = isset($postListType[$listType]) ? $postListType[$listType] : $postListType['0'];
        if($type == 'Locale'){
            $city = $this->base->load('ip')->find(common::getip());
            $type = 'Locale_'.md5($city[2]);
        }
        $redisKey = REDIS_PREFIX.'BoardPostList'.$boardId.'_'.$type;
        $limit = array(0, $offset);
        if($news_id > 0)
        {
            if($direc == 'next')
            {
                //24小时内showtime特殊排序
                $postList = [];
                /*
                if($boardId == 'showtime' && $type == 'New'){
                    $start = $this->redis->ZREVRANK($redisKey.'24H', $news_id);
                    if($start !== false){
                        $start += 1;
                        $stop = $start + $offset;
                        $postList = $this->redis->ZREVRANGE($redisKey.'24H', $start, $stop);
                        $count = $this->redis->zcard($redisKey.'24H');
                    }
                }
                */
                $_count = count($postList);
                if($_count < $offset){
                    if($_count){
                        $start = $count + 1;
                    }else{
                        $start = $this->redis->ZREVRANK($redisKey, $news_id) + 1;
                    }
                    $top = $start + $offset - $_count;
                    $postList = array_merge($postList,$this->redis->ZREVRANGE($redisKey, $start, $top));
                }
            }
            else
            {
                $start = $this->redis->ZRANK($redisKey, $news_id);
                $top = $start + $offset;
                $start += 1;
                $postList = $this->redis->ZRANGE($redisKey, $start, $top);
                krsort($postList);
            }
        }
        else
        {
            $channel = common::request('packageChannel', 'G','');
            $userInfo = $this->base->load('client')->getUserInfo($this->base->uid);
            $userChannel = isset($userInfo['fromChannel']) ? $userInfo['fromChannel'] : "";
            $channel = empty($channel) ? $userChannel : '';
            if(!empty($channel))
            {
                $channelPost = $this->redis->ZREVRANGEBYSCORE(REDIS_PREFIX.'ACT_'.$channel.'_'.$boardId, time(), '-inf');
            }
            //24小时内showtime特殊排序
            if($boardId=='showtime' && $type=='New'){
                //$postList = $this->redis->ZREVRANGE($redisKey.'24H', 0, $offset-1);
                $postList = [];
                $count = count($postList);
                if($count < $offset){
                    $postList = array_merge($postList,$this->redis->ZREVRANGE($redisKey, $count, $offset - $count -1));
                }
            }elseif(isset($city) && is_array($city) && $boardId=='showtime' ){
                $postList = $this->redis->ZREVRANGE($redisKey, 0, $offset-1);
                $count = count($postList);
                if($count<10){
                    $offset = 20 - $count;
                    $sql = "select city from r_city where `pro` like '{$city[1]}%'";
                    $cities = $this->db->getAll($sql);
                    $_postList = [];
                    foreach($cities as $row){
                        $_city = str_replace('市','',$row['city']);
                        if($_city==$city[2]){
                            continue;
                        }
                        $redisKey1 = REDIS_PREFIX.'BoardPostList'.$boardId.'_Locale_'.md5($_city);
                        $_postList = array_merge($_postList,$this->redis->zrevrange($redisKey1,0,$offset));
                    }
                    $postList = array_merge($postList,$_postList);
                    $postList = array_slice(array_unique($postList),0,$offset);
                }
            }else{
                $postList = $this->redis->ZREVRANGE($redisKey, 0, $offset-1);
            }
            if(isset($channelPost)) $postList = array_merge($channelPost, $postList);
        }

        return $postList;
    }
    /*
     * 获取帖子详情
     * @return $array
    */
    public function getPostInfo($news_id, $type=0)
    {
        $result = array();
        if($news_id)
        {
            $result = $this->redis->hgetall(REDIS_PREFIX. 'NewsInfo_' . $news_id);
            if(!$result)
            {
                $result = $this->db->getRowTable('r_news', array(), "news_id = '{$news_id}'");
                if($result)
                {
                    $this->redis->hmset(REDIS_PREFIX . 'NewsInfo_'. $news_id, $result);
                }
            }
            
            if($result)
            {
                $result['thumb_img'] = json_decode($result['thumb_img'], true);
                if(common::is_json($result['sourceImg']))
                {
                    $result['sourceImg'] = json_decode($result['sourceImg'], true);
                }
                else
                {
                    $result['sourceImg'] = array();
                }
                $result['nickname'] = $this->redis->hget(REDIS_PREFIX.'UserInfo_'.$result['uid'], 'nickname');
                $result['header'] = $this->redis->hget(REDIS_PREFIX.'UserInfo_'.$result['uid'], 'header');
                if(common::is_json($result['tag']))
                {
                    $tag = json_decode($result['tag'], true);
                    if(is_array($tag))
                    {
                        foreach ($tag as $key => $tagId) {
                            $tag[$key] = array();
                            $tag[$key]['tagId'] = $tagId;
                            $tag[$key]['tagName'] = $this->redis->hget(REDIS_PREFIX.'TagInfo_'.$tagId, 'tagName');
                        }
                    }
                    empty($tag) && $tag = array();
                }
                else
                {
                    $tag = array();
                }
                $result['tag'] = $tag;
                $board = isset($result['board']) ? json_decode($result['board'], true) : array();
                $temboard = array();
                if(is_array($board) && !empty($board))
                {
                    foreach ($board as $key => $boardId) {
                        if(!empty($boardId)){
                            $tem = array();
                            $tem['boardId'] = $boardId;
                            $tem['boardName'] = $this->redis->hget(REDIS_PREFIX.'BoardInfo_'.$boardId, 'boardName');
                            $temboard[] = $tem;
                            unset($tem);
                        }
                    }
                }
                $result['board'] = $temboard;
                $result['loves'] = isset($result['loves']) ? $result['loves'] : 0;
                // 帖子类型
                $result['type'] = isset($result['type']) ? $result['type'] : 1;
                // 帖子标题
                if(!$type && $this->base->vn < 2500 && !$result['title'])
                {
                    $result['title'] = $this->cutString($result['content'], 200);
                }
                //正能量
                if($this->base->vn >= 2820){
                    $result['energy'] = isset($result['energy']) ? $result['energy'] : 0;
                    $result['energy_pay_count'] = isset($result['energy_pay_count']) ? $result['energy_pay_count'] : 0;
                }
                $result['total_comment'] = isset($result['total_comment']) ? $result['total_comment'] : 0;
            }
        }
        return $result;
    }
    /**
     * 喜欢某帖子的用户列表
     * @param news_id 帖子id
     * @return
     */
    public function getPostLikeList($news_id, $point=0, $direc='next', $offset=20)
    {
        $result = array();
        $redisKey = REDIS_PREFIX.'PostLikeList_'.$news_id;

        if($point > 0)
        {
            if($direc == 'next')
            {
                $start = $this->redis->ZREVRANK($redisKey, $point);
                $top = $start + $offset;
                $start += 1;
                $users = $this->redis->ZREVRANGE($redisKey, $start, $top);
            }
            else
            {
                $start = $this->redis->ZRANK($redisKey, $point);
                $top = $start + $offset;
                $start += 1;
                $users = $this->redis->ZRANGE($redisKey, $start, $top);
                !empty($users) && krsort($users);
            }
        }
        else
        {
            $users = $this->redis->ZREVRANGE($redisKey, 0, $offset-1);
        }

        if($users)
        {
            foreach ($users as $uid) {
                $userInfo = $_ENV['client']->getUserInfo($uid);
                if($userInfo)
                {
                    $result[] = array(
                            'uid'      => $uid,
                            'levelInfo' => $_ENV['client']->getUserLevelInfo($uid),
                            'nickname' => $userInfo['nickname'],
                            'header' => $userInfo['header'],
                            'gender' => $userInfo['gender'],
                            'total_rate' => $userInfo['total_rate'],
                            'total_mileage' => sprintf("%.2f", $userInfo['total_mileage']),
                        );
                }
                unset($userInfo);
            }
        }
        return $result;
    }
    /**
     * 用户收藏列表
     * @param uid 用户id
     * @param news_id 帖子id
     * @param direc 数据追加方式
     * @param offset 数据条数
     * @return
     */
    public function getCollectionList($uid, $news_id = 0, $direc='next', $offset=20)
    {
        $result = array();
        $redisKey = REDIS_PREFIX.'CollectPostList_'.$uid;
        if($news_id > 0)
        {
            if($direc == 'next')
            {
                $start = $this->redis->ZREVRANK($redisKey, $news_id);
                $top = $start + $offset;
                $start += 1;
                $postList = $this->redis->ZREVRANGE($redisKey, $start, $top);
            }
            else
            {
                $start = $this->redis->ZRANK($redisKey, $news_id);
                $top = $start + $offset;
                $start += 1;
                $postList = $this->redis->ZRANGE($redisKey, $start, $top);
                !empty($postList) && krsort($postList);
            }
        }
        else
        {
            $postList = $this->redis->ZREVRANGE($redisKey, 0, $offset-1);
        }
        if($postList)
        {
            foreach ($postList as $news_id) {
                $postInfo = $this->getPostInfo($news_id);
                if($postInfo && $postInfo['is_show'])
                {
                    $result[] = array(
                            'news_id'   => $news_id,
                            'title' => $postInfo['title'] ? $postInfo['title'] : $this->cutString($postInfo['content'], 200),
                            'thumb_img' => empty($postInfo['thumb_img']) ? '' : $postInfo['thumb_img'][0],
                            'header' => $this->redis->hget(REDIS_PREFIX.'UserInfo_'.$postInfo['uid'], 'header').'',
                            'nickname' => $this->redis->hget(REDIS_PREFIX.'UserInfo_'.$postInfo['uid'], 'nickname').'',
                            'uid' => $postInfo['uid'],
                            'add_time' => $this->redis->ZSCORE($redisKey, $news_id)
                        );
                }
                else
                {
                    $this->redis->ZREM($redisKey, $news_id);
                }
                unset($userInfo);
            }
        }
        !$result && $result = array();
        return $result;
    }
    /*
     * 生成用户收藏REDIS数据
     * @return $array
    */
    public function createUserCollectList()
    {
        $redisKey = REDIS_PREFIX.'CollectPostList_';
        $collection = $this->db->getAll("select uid, news_id, add_time from r_news_collection where is_delete = 0");
        if($collection)
        {
            foreach ($collection as $v) {
                $this->redis->ZADD($redisKey.$v['uid'], $v['add_time'], $v['news_id']);
            }
        }
        return ;
    }
    /*
     * 获取某帖子的热门评论
     * @return $array
    */
    public function getHotComment($news_id)
    {
        $result = $this->redis->get(REDIS_PREFIX .'hotCommentList'.$news_id);
        if(common::is_json($result))
        {
            $uid = $this->base->uid;
            $authorId = $this->redis->hget(REDIS_PREFIX.'NewsInfo_'.$news_id, 'uid');
            $result = json_decode($result, true);
            if($result)
            {
                foreach ($result as & $v)
                {
                    $v['is_lighten'] = $this->redis->hexists(REDIS_PREFIX.'NewsCommentLight'.$v['comment_id'], $uid) ? 1 : 0;
                    $v['isLandlord'] = ($authorId > 0 && $authorId == $v['uid']) ? 1 : 0;
                }
            }
        }
        (!is_array($result) || empty($result)) && $result = array();
        return $result;
    }
    /**
     * 更新某资讯的热门评论
     * @int news_id 帖子id
     * @return
     */
    public function updateHotComment($news_id, $limit = 20)
    {
        $upLimit = $this->base->config['NEWS_HOT_COMMENT_LIMIT'];
        $result = $this->db->getAll("select * from r_news_comment where is_show = 1 and news_id = '{$news_id}' and lights >= '{$upLimit}' order by lights DESC limit $limit");
        if($result)
        {
            $authorId = $this->redis->hget(REDIS_PREFIX.'NewsInfo_'.$news_id, 'uid');
            empty($authorId) && $authorId = -1;
            $user = $this->base->uid;
            empty($user) && $user = 0;
            foreach ($result as $key => & $v) {
                $v['nickname'] = $this->redis->hget(REDIS_PREFIX.'UserInfo_'.$v['uid'], 'nickname');
                $v['header'] = $this->redis->hget(REDIS_PREFIX.'UserInfo_'.$v['uid'], 'header');
                $v['floor'] = $this->redis->zrank(REDIS_PREFIX.'NewsComFloor_'.$news_id, $v['comment_id'])+1;
            }
        }
        $this->redis->set(REDIS_PREFIX .'hotCommentList'.$news_id, json_encode($result));
        return $result;
    }
    /**
     * 获取版块信息及版块下标签列表
     * @int/array() board 版块id或包含版块id数组
     * @return
     */
    public function getTagList($board)
    {
        $result = array();
        if(is_array($board))
        {
            foreach ($board as $boardId) {
                $list = $this->getTagList($boardId);
                !empty($list) && $result[] = $list;
                unset($list);
            }
        }
        else
        {
            $boardInfo = $this->getBoardInfo($board);
            if(!empty($boardInfo))
            {
                $result['boardInfo']['boardId'] = $boardInfo['boardId'];
                $result['boardInfo']['boardName'] = $boardInfo['boardName'];
            }
            $result['boardInfo'] = $boardInfo;
            $result['tagList'] = $this->getBoardTagList($board);
        }
        return $result;

    }
    /**
     * 获取版块下标签列表
     * @int $boardId 版块id
     * @boolen $isAdmin 是否后台请求
     * @return
     */
    public function getBoardTagList($boardId, $isAdmin = false)
    {
        $result = array();
        $tagList = $this->redis->ZREVRANGEBYSCORE(REDIS_PREFIX.'BoardTagList_'.$boardId, '+inf', '-inf');
        if(empty($tagList))
        {
            $tagList = $this->db->getCol("select tagId from r_boardtag where boardId = '{$boardId}'");
            $insertRedis = true;
        }
        if(!empty($tagList))
        {
            foreach ($tagList as $tagId) {
                $tagInfo = $this->getTagInfo($tagId, $isAdmin);
                if(!empty($tagInfo)){
                    $tagInfo['style'] = json_decode($tagInfo['style'], true);
                    $result[] = $tagInfo;
                    if(isset($insertRedis)) $this->redis->ZADD(REDIS_PREFIX.'BoardTagList_'.$boardId, $tagId, $tagId);
                }
                unset($tagInfo);
            }
        }
        return $result;
    }
    /**
     * 获取标签信息
     * @int $tagId 标签id
     * @boolen $isAdmin 是否后台请求
     * @return
     */
    public function getTagInfo($tagId, $isAdmin = false)
    {
        $tagId = intval($tagId);
        $tagInfo = $this->redis->hgetall(REDIS_PREFIX.'TagInfo_'.$tagId);
        if(empty($tagInfo))
        {
            $tagInfo = $this->db->getRowTable('r_tag', array(), "tagId = '{$tagId}'");
            if($tagInfo)
            {
                $this->redis->hmset(REDIS_PREFIX.'TagInfo_'.$tagId, $tagInfo);
            }
        }
        if(!empty($tagInfo) && $isAdmin === false)
        {
            unset($tagInfo['uid'],$tagInfo['addTime']);
        }
        !$tagInfo && $tagInfo = array();
        return $tagInfo;
    }
    /*
     * 获取标签下帖子列表
     * @return $array
    */
    public function getTagPostList($tagId, $listType=0, $news_id=0, $direc ='next', $offset = 10)
    {
        $result = array();
        $postListType = common::$postListType;
        $type = isset($postListType[$listType]) ? $postListType[$listType] : $postListType['0'];
        $redisKey = REDIS_PREFIX.'TagPostList'.$tagId.'_'.$type;
        $limit = array(0, $offset);
        if($news_id > 0)
        {
            if($direc == 'next')
            {
                $start = $this->redis->ZREVRANK($redisKey, $news_id);
                $top = $start + $offset;
                $start += 1;
                $result = $this->redis->ZREVRANGE($redisKey, $start, $top);
            }
            else
            {
                $start = $this->redis->ZRANK($redisKey, $news_id);
                $top = $start + $offset;
                $start += 1;
                $result = $this->redis->ZRANGE($redisKey, $start, $top);
                krsort($result);
            }
        }
        else
        {
            $channel = common::request('packageChannel', 'G','');
            if(!empty($channel)){
                $channelPost = $this->redis->ZREVRANGEBYSCORE(REDIS_PREFIX.'ACT_'.$channel.'_'.$tagId, time(), '-inf');
            }
            $result = $this->redis->ZREVRANGE($redisKey, 0, $offset-1);
            if(isset($channelPost)) $result = array_merge($channelPost, $result);
        }

        return $result;
    }
    /**
     * 获取某帖子的评论列表
     * @int news_id 帖子id
     * @string type 评论类型 all hot
     * @int point  界限点：一个评论ID
     * @int direc  数据加载方式  next prev
     * @int offset  要获取的评论数量
     * @int p  页码
     * @return array()
     */
    public function getCommentList($news_id, $point = 0, $direc = 'next',$offset = 10,$p = 0)
    {
        $result = array();
        if($news_id)
        {
            empty($offset) && $offset = 10;
            $sql = "select * from r_news_comment where news_id = {$news_id} ";
            $count_sql = "select count(comment_id) from r_news_comment where news_id = {$news_id} ";
            if($p >0)
            {
                //分页
                require FILE . 'lib/page.class.php';
                $num = $this->base->db->getone($count_sql);
                $offset = empty($offset) ? 10 : $offset;
                $page = new Page($num, $offset);
                $pageStr = $page->show();
                $this->base->view->assign('pageStr', $pageStr);

                $start = ($p-1) * $offset;
                $sql .= $type == 'hot' ? ' order by lights DESC' : ' order by comment_id DESC';
                $sql .= " limit {$start}, {$offset}";
            }
            else
            {
                $sql .= ' and is_show = 1';
                if($point > 0)
                {
                    $sql .= " and comment_id ";
                    $sql .= $direc == 'prev' ? "> {$point} order by comment_id ASC" : "< {$point} ORDER BY comment_id DESC";
                }
                else
                {
                    $sql .= ' ORDER BY comment_id DESC';
                }
                $sql .=" limit {$offset}";
            }
            $result = $this->db->getall($sql);
        }
        if($result)
        {
            $point > 0 && $direc == 'prev' && rsort($result);
            $authorId = $this->redis->hget(REDIS_PREFIX.'NewsInfo_'.$news_id, 'uid');
            empty($authorId) && $authorId = -1;
            $user = $this->base->uid;
            empty($user) && $user = 0;
            foreach ($result as $k => & $v) {
                $v['floor'] = $this->redis->zrank(REDIS_PREFIX.'NewsComFloor_'.$news_id, $v['comment_id'])+1;
                $v['nickname'] = $this->redis->hget(REDIS_PREFIX . 'UserInfo_' . $v['uid'], 'nickname');
                $v['header'] = $this->redis->hget(REDIS_PREFIX . 'UserInfo_' . $v['uid'], 'header');
                $v['is_lighten'] = $this->redis->hexists(REDIS_PREFIX.'NewsCommentLight'.$v['comment_id'], $user) ? 1 : 0;
                $v['isLandlord'] = $authorId == $v['uid'] ? 1 : 0;
            }
        }
        return $result;
    }
    /**
     * 获取某帖子的评论列表（无图的）
     * @int news_id 帖子id
     * @int offset  要获取的评论数量
     * @return array()
     */
    public function getCommentsNoImg($news_id, $offset = 4)
    {
        $result = array();
        if($news_id)
        {
            empty($offset) && $offset = 4;
            $sql = "select uid, comment_content from r_news_comment where news_id = {$news_id} and is_show = 1 and comment_img = '' ORDER BY comment_id DESC limit {$offset}";

            $result = $this->db->getall($sql);
        }
        if($result)
        {
            foreach ($result as & $v)
            {
                $v['nickname'] = $this->redis->hget(REDIS_PREFIX . 'UserInfo_' . $v['uid'], 'nickname');
                $v['content'] = $v['comment_content'];
                unset($v['comment_content'], $v['uid']);
            }
        }
        return $result;
    }

    /**
     * 获取发布帖子时图片的原图、缩略图、图片html
     * @string $inputName 字段名前段
     * @return array('sourceImg','thumbImg', 'imgHtml')
     */
    public function getPostImage($inputName, $num=6, $thumbNum = 6)
    {
        $sourceImg = array();  // 原图
        $thumbImg = array();   // 缩略图
        $imgHtml = '';         // 将图片格式化为html
        $validImg = array();
        
        $this->base->load('qiniu');
        for($i = 0; $i< $num ; $i++)
        {
            if (isset($_FILES[$inputName.$i]) && $_FILES[$inputName.$i]['error'] == 0 && in_array($_FILES[$inputName.$i]['type'], array('image/png', 'image/gif', 'image/jpeg')))
            {
                $name = md5(time().$i.common::getHashStr(5));
                $img = $_ENV['qiniu']->uploadQiNiuImg($inputName.$i, $name);

                if(!$img)
                {
                    continue;
                }
                // 生成图片名
                $imgNameArr = explode('.', $_FILES[$inputName.$i]['name']);
                $imgName = $name.'.'.strtolower(end($imgNameArr));

                $sourceImg[] = $img;
                $midImg = $img.'?imageView2/2/w/720';
                if(count($thumbImg) < $thumbNum)
                {
                    if(!empty($img))
                    {
                        $tmpImg = $this->qiNiuCropImg($img, getimagesize($_FILES[$inputName.$i]['tmp_name']), 'thumb'.$imgName);
                        $_FILES[$inputName.$i]['type'] == 'image/gif' && $tmpImg = $this->qiNiuWaterMark($tmpImg);
                        $thumbImg[] = $tmpImg;
                    }
                    //unset($tmpImg);
                }
                $imgHtml .= '<p style="margin:5px auto;"><a href="joggers://topic/image/'.$img.'"><img src="'.$midImg.'" style="max-width:100%;" /></a></p>';
                // $validImg[] = array('inputName' => $inputName.$i,  'name' => $name);
            }
        }
        return compact('sourceImg', 'thumbImg', 'imgHtml', 'validImg');
    }
    /**
     * 生成 html 格式的内容，非图文混排帖子突出图片
     * @ $content 帖子内容
     * @return string 
     */
    public function buildPostContent($content, $sourceImg = array())
    {
        $result = '<p>'.$content.'</p>';

        $imgHtml = '';
        // 图片生成html格式的内容
        foreach ($sourceImg as $img)
        {
            $midImg = $img.'?imageView2/2/w/720';
            $imgHtml .= '<p style="margin:5px auto;"><a href="joggers://topic/image/'.$img.'"><img src="'.$midImg.'" style="max-width:100%;" /></a></p>';
        }
        $result .= $imgHtml;

        return $result;
    }
    
    /*
     * 标记话题
     */
    public function buildPostTopic($content){
        //突出话题
        $clean_content = strip_tags($content,'<widget>');
        preg_match_all("/#.*?#/",$clean_content,$matches);
        $_matches = array_unique($matches[0]);
        foreach($_matches as $match){
            $content = str_replace($match,'<a class="topic" href="joggers://topicSearch/'.$match.'">'.$match.'</a>',$content);
        }
        return $content;
    }
    
    /*
     * 解析卡片widget
     */
    public function buildWidget($content,$news_id,$plantform){
        $host = $this->base->config['host'];
        $template = '
        <a href="%s" style="text-decoration: none"><div> <table class="widget" data-newsid="'.$news_id.'">
      <tr>
        <td rowspan="2" valign="top"><img src="%s"></td>
        <td width="600">
          <h6>%s</h6>
        </td>
      </tr>
      <tr>
        <td>
          <p class="price">
            ¥%s
            <input type="button" name="" value="去购买">
          </p>
        </td>
      </tr>
    </table></div></a>';
        preg_match_all("/<widget .*?><\/widget>/",$content,$matches);
        $gear_mod = $this->base->load('gear');
        $isMath = false;
        foreach($matches[0] as $key=>$fullMatch){
            $xml = simplexml_load_string($fullMatch);
            if(!$xml){
                continue;
            }
            $elements = $xml->attributes();
            $type = $elements['template'];
            if($type=='groupon'){
                $goodsInfo = array();
                $url = 'http://'.$host.'/show/groupondetail?flashId='
                    .$elements['supplier_id'].'&_track=taokenewsdetail';
                $groupon = $gear_mod->getGrouponDetail($elements['supplier_id']);
                if($groupon['status']!=0 && $groupon['status']!=5){
                    continue;
                }
                $goodsInfo['image'] = $groupon['image'];
                $goodsInfo['title'] = $groupon['title'];
                $goodsInfo['price'] = $groupon['low_price'];
            }else if($type=='taobao'){
                $goodsInfo = array();
                $taobaoChannel = $gear_mod->getTaobaoChannel($elements['channel_id']);
                if(!empty($taobaoChannel)) {
                    $goodsInfo['image'] = $taobaoChannel['pic'];
                    $goodsInfo['title'] = $elements['title'];
                    $goodsInfo['price'] = $taobaoChannel['price'];
                    $goodsInfo['item_id'] = $taobaoChannel['item_id'];
                    $url = $gear_mod->getGoodsChannelUrl($goodsInfo, $plantform, $news_id);
                }
            }else {
                $goodsInfo = $gear_mod->getGoodsInfo($elements['gear_id'], $elements['supplier_id']);
                if (empty($goodsInfo)) {
                    continue;
                }
                $goodsInfo['images'] = json_decode($goodsInfo['images'], true);
                $goodsInfo['image'] = current($goodsInfo['images']);
                $url = $gear_mod->getGoodsChannelUrl($goodsInfo, $plantform, $news_id);
            }

            if(!empty($goodsInfo)) {
                $html = sprintf($template, $url, $goodsInfo['image'], $elements['title'], $goodsInfo['price']);
                $content = str_replace($fullMatch, $html, $content);
                $isMath = true;
            }
        }
        $css = '<style type="text/css">
            .widget {
                min-height: 85px; margin:0px; padding: 5px 5px 5px 100px; 
                background:#f6f7fb; border:1px solid #e6e7e9; position: relative;   display: -webkit-box;
                -webkit-box-sizing: initial;box-sizing: initial;
            }
            
            .widget img {width: 85px; position: absolute; top: 5px; left: 5px;margin:0px;border:0px;height:auto;}
            .widget div { width: 100% }
     
            .widget h6 { 
                font-size: 100%;color:#4f4f4f; 
                overflow : hidden;
                text-overflow: ellipsis;
                display: -webkit-box;
                -webkit-line-clamp: 2;
                -webkit-box-orient: vertical;
                -moz-line-clamp: 2;
                -moz-box-orient: vertical;
                -o-line-clamp: 2;
                -o-box-orient: vertical;
                margin:0; padding-top:10px;font-weight:normal;
                }
            .widget p{margin:0px;padding:0px;}
            .widget input[type=button] {
                background:#eb4f3f;border-radius:6px;width:60px;height:28px; font-size: 13px; 
                color: #fff; position:  ; right: 0px; bottom: 0px;
                -webkit-appearance:none;border:none;
                outline:none
                }
             .widget .btn-p { position: relative; padding-top:5px;padding-right: 70px;  }
             .widget .price { height:40px;min-height: 30px;line-height:40px;color:#d93b3b ;text-align: right;padding-right:5px;color:#d93b3b ;}
             .widget a{text-decoration: none}
        </style><iframe id="ifr" width="100" height="100" style="display:none" src="http://'.$host.'/show/gearNewsTj?newsid='.$news_id.'"></iframe>
         <script type="text/javascript">
window.onload = function() {
    var ifr = document.getElementById("ifr");
    var targetOrigin = "http://'.$host.'"; 
    var widgets = document.getElementsByClassName("widget");
    for(var i=0;i<widgets.length;i++){ 
        var newsid = widgets[i].getAttribute("data-newsid");
        widgets[i].onclick = function(){
            ifr.contentWindow.postMessage({et:"newschannel",id:newsid}, targetOrigin);
        }
    }
};
</script>';
        return $isMath? $css.$content : $content;
    }

    /**
     * 七牛裁剪图片(为正方形)并做持久化处理
     * @string $imgUrl  图片地址（七牛）
     * @arraay() $size 原图尺寸 array('width', 'height')
     * @string $newImgName 新图片名
     * @return string $newImg
    */
    public function qiNiuCropImg($imgUrl, $size, $newImgName='', $thumbSize = '200x200')
    {
        $result = false;
        if(is_array($size) && !empty($size))
        {
            $width = $size[0];
            $height = $size[1];
            $wOffset = 0;
            $hOffset = 0;
            $cropstr = '';
            extract($this->base->config['qiniu']);
            $newImgName == '' && $newImgName = 'thumb'.str_replace('http://'.$bucket.'.'.$host, '', $imgUrl);
            $imgInfo = @json_decode(common::getContents($imgUrl.'?imageInfo'), true);
            $isGif = false;
            if(is_array($imgInfo) && isset($imgInfo['format']) && $imgInfo['format'] == 'gif')
            {
                $newImgName = str_ireplace('.gif', '.jpg', $newImgName);
                $isGif = true;
            }
            if($width > $height)
            {
                $wOffset = intval(($width-$height)/2);
                $cropstr = '!'.$height.'x'.$height;
            }
            else if($width < $height)
            {
                $hOffset = intval(($height-$width)/2);
                $cropstr = '!'.$width.'x'.$width;
            }
            else
            {
                if(!$isGif)
                {
                    require_once("static/qiniusdk/qiniu/rs.php");
                    Qiniu_SetKeys($accessKey, $secretKey);
                    $key = str_replace('http://'.$bucket.'.'.$host, '', $imgUrl);
                    $client = new Qiniu_MacHttpClient(null);
                    $err = Qiniu_RS_Copy($client, $bucket, $key, $bucket, $newImgName);
                    if($err !== null)
                    {
                        return '';
                    }
                    else
                    {
                        return 'http://'.$bucket.'.'.$host.$newImgName;
                    }
                }
            }
            //生成EncodedEntryURI的值
            $encodedEntryURI=common::urlsafe_base64_encode("$bucket:$newImgName");
            if($width != $height)
            {
                $cropstr .= 'a'.$wOffset.'a'.$hOffset;
                //使用SecretKey对新的下载URL进行HMAC1-SHA1签名
                $newurl = str_replace('http://', '', $imgUrl).'?imageMogr2/crop/'.$cropstr;
                $isGif != false && $newurl .= '/format/jpg';
            }
            else // 长宽相等且是gif图，转换为jpg格式后做持久化处理
            {
                $newurl = str_replace('http://', '', $imgUrl).'?imageMogr2/format/jpg';
            }
            $newurl .= '/thumbnail/'.$thumbSize.'!';
            $newurl .= '|saveas/'.$encodedEntryURI;
            $sign = hash_hmac("sha1", $newurl,$secretKey, true);

            //对签名进行URL安全的Base64编码
            $encodedSign = common::urlsafe_base64_encode($sign);

            //最终得到的完整下载URL
            $data = common::getContents("http://".$newurl."/sign/".$accessKey.":".$encodedSign);
            $data = json_decode($data, true);
            if(isset($data['key']))
            {
                $result = 'http://'.$bucket.'.'.$host.$data['key'];
            }
        }
        return $result;
    }
    /**
     * 七牛裁剪图片添加水印
     * @string $imgUrl  图片地址（七牛）
     * @
     * @
     * @return string $imgUrl
    */
    public function qiNiuWaterMark($imgUrl)
    {
        $result = '';
        $markUrl = 'http://'.$this->base->config['host'].'/static/backend/mark.png';
        extract($this->base->config['qiniu']);
        $imgUrl = str_replace('http://', '', $imgUrl);
        $imgName = str_replace($bucket.'.'.$host, '', $imgUrl);
        //生成EncodedEntryURI的值
        $encodedEntryURI=common::urlsafe_base64_encode("$bucket:$imgName");

        $imgUrl .= '?watermark/1/image/'.common::urlsafe_base64_encode($markUrl).'/dissolve/100/gravity/SouthEast/dx/0/dy/0|saveas/'.$encodedEntryURI;
        $sign = hash_hmac("sha1", $imgUrl,$secretKey, true);
        //对签名进行URL安全的Base64编码
        $encodedSign = common::urlsafe_base64_encode($sign);

        //最终得到的完整下载URL
        $data = common::getContents("http://".$imgUrl."/sign/".$accessKey.":".$encodedSign);
        $data = json_decode($data, true);
        if(isset($data['key']))
        {
            $result = 'http://'.$bucket.'.'.$host.$data['key'];
        }
        return $result;
    }
    /**
     * 发表帖子
     * @param $type 帖子类型 1：图片混排， 0：非图文混排
     * @return
     */
    public function addPost($boardId, $uid, $title, $content, $short_desc='',$sourceImg=array(),$thumb_img=array(), $tag='[]', $validImg,$type = 1,$gid=0,$source='',$lat=0,$lng=0,$source_client=0,$is_show=1)
    {
        $result = false;
        if(empty($boardId) || empty($uid))
        {
            return $result;
        }
        if($this->redis->zscore(REDIS_PREFIX.'BoardList', $boardId) === false && $boardId != 'groupNews')
        {
            return false;
        }

        $type != 1 && $type = 0;
        if($gid >0 && !empty($source)){
            $data = json_decode($source);
            $data[] = $boardId;
            $board = json_encode($data);
        }else{
            $board = '["'.$boardId.'"]';
        }

        $tag = $this->checkTag(json_decode($tag, true));
        $author = $this->redis->hget(REDIS_PREFIX.'UserInfo_'.$uid, 'nickname');
        $add_time = $real_addtime = $lastupdate = time();
        //$is_show = 1;
        $start_time = 0;
        $loves = $total_comment = $is_top = $a_start_time = $a_end_time = 0;
        $a_channel = '';
        $imgCount = count($thumb_img);
        $imgCount > 3 && $imgCount = 3;
        $imginfo = array();
        for($i=0;$i<count($sourceImg);$i++){
            $info = getimagesize($sourceImg[$i]);
            //if(!empty($info)){
                $imginfo[$i]['width'] = isset($info[0]) ? $info[0] : 450;
                $imginfo[$i]['height'] = isset($info[1]) ? $info[1] : 450;
            //}
        }
        $redata['img'] = !empty($thumb_img) ? $thumb_img['0'] : '';
        $imginfo = json_encode($imginfo);
        $sourceImg = json_encode($sourceImg);
        $thumb_img = json_encode($thumb_img);
        $ip = common::getip();
        $city = $this->base->load('ip')->find($ip);
        $city = $city[2] ? $city[2] : null;
        $data = compact('type', 'uid','board','title','short_desc','content','thumb_img','sourceImg','tag','author','add_time','real_addtime','lastupdate','is_show','start_time','loves','total_comment','loves','imgCount','is_top','a_channel','a_start_time','a_end_time','imginfo','lat','lng','ip','city','source_client');
        
        $news_id = $this->insert($data);
        if($news_id)
        {
            if($this->base->vn >= 2700){
                $redata['news_id'] = "$news_id";
                $redata['title'] = $title;
                $this->base->result['result'] = $redata;
            }else{
                $this->base->result['result']['is_success'] = 1;
            }
            $this->base->breakCall();
            // 正能量
            $_ENV['client']->userEnergyChange($uid, 'post',$news_id);
            $data['news_id'] = $news_id;
            $data['sourceImg'] = $sourceImg;
            $this->redis->hmset(REDIS_PREFIX.'NewsInfo_'.$news_id, $data);
            if($boardId && $gid <= 0)
            {
                $this->db->insertRowTable('r_boardPost', compact('boardId', 'news_id'));
                $this->redis->zadd(REDIS_PREFIX.'BoardPostList'.$boardId.'_New', $add_time, $news_id);
                $this->redis->zadd(REDIS_PREFIX.'BoardPostList'.$boardId.'_Hot', 0, $news_id);
                if($boardId=='showtime'){
                    //24小时内排序
                    $author_gender = $this->redis->hget(REDIS_PREFIX.'UserInfo_'.$uid, 'gender');
                    if($author_gender == 1){
                        $score = $add_time;
                    }elseif($author_gender == 2){
                        $score = $add_time+20000000000;
                    }else{
                        $score = $add_time+10000000000;
                    }
                    //清除旧数据
                    //$this->redis->ZREMRANGEBYSCORE(REDIS_PREFIX.'BoardPostList'.$boardId.'_New24H',$add_time-48*3600,$add_time-24*3600);
                    //$this->redis->ZREMRANGEBYSCORE(REDIS_PREFIX.'BoardPostList'.$boardId.'_New24H',$add_time-48*3600+10000000000,$add_time-24*3600+10000000000);
                    //$this->redis->ZREMRANGEBYSCORE(REDIS_PREFIX.'BoardPostList'.$boardId.'_New24H',$add_time-48*3600+20000000000,$add_time-24*3600+20000000000);
                    
                    //$this->redis->zadd(REDIS_PREFIX.'BoardPostList'.$boardId.'_New24H',$score,$news_id);
                    
                    //同城
                    $city = $this->base->load('ip')->find(common::getip());
                    if($city[2]){
                        $this->redis->zadd(REDIS_PREFIX.'BoardPostListshowtime_Locale_'.md5($city[2]),$add_time,$news_id);
                    }
                }
            }
            if($tag != '[]')
            {
                foreach (json_decode($tag, true) as $tagId)
                {
                    $this->db->insertRowTable('r_tagPost', compact('tagId', 'news_id'));
                    $this->redis->zadd(REDIS_PREFIX.'TagPostList'.$tagId.'_New', $add_time, $news_id);
                    $this->redis->zadd(REDIS_PREFIX.'TagPostList'.$tagId.'_Hot', 0, $news_id);
                }
            }
            if($gid > 0){
                $insertData = compact('news_id','uid','gid');
                $insertData['addtime'] = $add_time;
                $this->db->insertRowTable('r_group_news',$insertData);
                $this->redis->zadd(REDIS_PREFIX.'GroupNews_'.$gid,$add_time,$news_id);
                if(strpos($board,'showtime') !== false){
                    $bData['boardId'] = "showtime";
                    $bData['news_id'] = $news_id;
                    $this->db->insertRowTable('r_boardPost', $bData);
                    $this->redis->zadd(REDIS_PREFIX.'BoardPostListshowtime_New', $add_time, $news_id);
                    $this->redis->zadd(REDIS_PREFIX.'BoardPostListshowtime_Hot', 0, $news_id);
                }
            }
            
            $this->base->load('topic')->filterPost($data);
        }
        return $news_id;
    }
     /**
     * 截断字符串
     * @string $string
     * @int  length  要获取的内容最大长度
     * @return string $result
     */
    public function cutString($string, $length = 100, $dot = '...', $charset = 'utf-8')
    {
        $string = strip_tags($string);
        if(strlen($string) <= $length) {
            return $string;
        }
        $string = str_replace(array('　',' ', '&', '"', '<', '>'), array('','','&', '"', '<', '>'), $string);
        $result = '';
        if(strtolower($charset) == 'utf-8')
        {
            $n = $tn = $noc = 0;
            while($n < strlen($string))
            {
                $t = ord($string[$n]);
                if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
                    $tn = 1; $n++; $noc++;
                } elseif(194 <= $t && $t <= 223) {
                    $tn = 2; $n += 2; $noc += 2;
                } elseif(224 <= $t && $t < 239) {
                    $tn = 3; $n += 3; $noc += 2;
                } elseif(240 <= $t && $t <= 247) {
                    $tn = 4; $n += 4; $noc += 2;
                } elseif(248 <= $t && $t <= 251) {
                    $tn = 5; $n += 5; $noc += 2;
                } elseif($t == 252 || $t == 253) {
                    $tn = 6; $n += 6; $noc += 2;
                } else {
                    $n++;
                }
                if($noc >= $length) {
                    break;
                }
            }
            if($noc > $length) {
                $n -= $tn;
            }
            $result = substr($string, 0, $n);
        } else {
            for($i = 0; $i < $length; $i++) {
                $result .= ord($string[$i]) > 127 ? $string[$i].$string[++$i] : $string[$i];
            }
        }
        strlen($string) > strlen($result) && $result .= $dot;
        return $result;
    }
    /**
     * 发布评论
     * @param news_id 帖子id
     * @param comment_content 评论内容
     * @param father_id 父级评论id
     * @return int  comment_id  生成的评论id
     */
    public function publishComment($news_id, $comment_content, $uid, $father_id = 0, $comment_img = '',$source='')
    {
        $result = false;
        $postInfo = $this->getPostInfo($news_id);
        if(!empty($postInfo) && $postInfo['is_show'] == 1 && $uid)
        {
            if(!empty($father_id))
            {
                $father_uid = $this->db->getone("select uid from r_news_comment where news_id = {$news_id} and comment_id = {$father_id} limit 1");
                if(empty($father_uid))
                {
                    $_ENV['error']->getErrors(101);
                    exit();
                }
            }
            $img_size = empty($comment_img) ? array() : getimagesize($_FILES['comment_img']['tmp_name']);
            if(!empty($img_size) && !empty($comment_img))
            {
                $w = $img_size[0];
                $h = $img_size[1];
                $thumbInfo = $this->base->load('news')->getThumbInfo($w, $h);
                extract($thumbInfo);
                $thumb_img = empty($thumb_img) ? $comment_img : $comment_img .'?imageMogr2/thumbnail/'.$thumb_img;
            }
            else
            {
                $thumb_size = '0x0';
                $thumb_img = '';
            }
            $add_time = time();
            $comment = compact('news_id','father_id','uid','comment_content','add_time', 'comment_img','thumb_img','thumb_size');
            $new_comment_id = $this->db->insertRowTable('r_news_comment', $comment);
            if($new_comment_id)
            {
                // 评论楼层
                $this->redis->zadd(REDIS_PREFIX.'NewsComFloor_'.$news_id, $new_comment_id, $new_comment_id);
                $floor = $this->redis->zrank(REDIS_PREFIX.'NewsComFloor_'.$news_id, $new_comment_id)+1;
                $this->base->result['result'] = compact('new_comment_id' ,'floor','comment_img','thumb_img','comment_content', 'thumb_size');
                $this->base->breakCall();
                $this->redis->HINCRBY(REDIS_PREFIX. 'NewsInfo_'.$news_id, 'total_comment', 1);
                //$this->db->update("update r_news set total_comment = total_comment+1 where news_id = '{$news_id}'");
                $this->update(['total_comment'=>'?+1','news_id'=>$news_id]);
                // 更新版块最热列表
                if(!empty($postInfo['board']))
                {
                    foreach ($postInfo['board'] as $board) {
                        $this->redis->ZADD(REDIS_PREFIX.'BoardPostList'.$board['boardId'].'_Hot', time(), $news_id);
                    }
                }
                // 更新标签最热列表
                if(!empty($postInfo['tag']))
                {
                    foreach ($postInfo['tag'] as $tag) {
                        $this->redis->ZADD(REDIS_PREFIX.'TagPostList'.$tag['tagId'].'_Hot', time(), $news_id);
                    }
                }
                // 增加正能量
                $this->base->load('client')->userEnergyChange($uid, 'comment',$new_comment_id);
                if($uid != $postInfo['uid'])
                {
                    $this->addUnReadMsg($postInfo['uid'], array('msgType'=>1, 'sponsor'=>array('uid'=>$uid,'comment_id'=>$new_comment_id), 'quote'=>array('news_id'=>$news_id,'comment_id'=>'0')));

                    //发送IM消息
                    if(!$father_id){
                        $this->sendMessage($uid, $postInfo['uid'],$news_id,$new_comment_id,$comment_content,"N2",'',$source);
                    }
                }
                if($father_id > 0 && $uid != $father_uid)
                {
                    $this->addUnReadMsg($father_uid, array('msgType'=>2, 'sponsor'=>array('uid'=>$uid,'comment_id'=>$new_comment_id), 'quote'=>array('news_id'=>$news_id,'comment_id'=>$father_id)));

                    //发送IM消息
                    $this->sendMessage($uid, $father_uid,$news_id,$new_comment_id,$comment_content,"N4",'',$source);

                }
            }
            else
            {
                $_ENV['error']->getErrors(100);
                exit;
            }
        }
        else
        {
            $_ENV['error']->getErrors(101);
            exit();
        }
    }

    /**
     * 发送跑步有道消息
     * @param  [type] $toUserId [description]
     * @param  [type] $data     [description]
     * @return [type]           [description]
     */
    public function sendMessage($fromUserId,$toUserId, $newsId, $commentId, $content, $descType, $gid='',$source=''){
        
    
        $category = "2";
        $send_id = "S10002";
        $source_id = $fromUserId; 
        $target_id = $toUserId;
        $descType = $descType;
        $contentArr = array(
            "news_id" => $newsId,
            "comment_id" => $commentId,
            "content" => $content,
            "gid" => $gid,
            'source'=>$source //来源
        );
        $content = json_encode($contentArr);
        $this->base->load('message')->insertMessage($category, $send_id ,$source_id ,$target_id , $descType,$content);
    }

    /**
     * 喜欢某帖子
     * @param news_id 帖子id
     * @param uid  用户ID
     * @return record_id  记录ID
     */
    public function likePost($news_id, $uid)
    {
        $record_id = 0;

        $add_time = time();
        $is_delete = 0;
        $likeArray = compact('news_id','uid','add_time' ,'is_delete');
        $record_id = $this->db->insertRowTable('r_news_likes', $likeArray);

        $postInfo = $this->getPostInfo($news_id);

        return $record_id;
    }
    /**
     * 取消喜欢某帖子
     * @param news_id 帖子id
     * @param uid  用户ID
     * @return
     */
    public function unlikePost($news_id, $uid)
    {
        $result = 1;
        $is_delete = 1;
        $likeArray = compact('news_id','uid','is_delete');
        if($this->db->updateRowTable('r_news_likes', $likeArray) === false)
        {
            $result = 0;
        }
        return $result;
    }
    /**
     * 收藏某帖子
     * @param news_id 帖子id
     * @param uid  用户ID
     * @return collection_id  记录ID
     */
    public function collectPost($news_id, $uid)
    {
        $collection_id = 0;

        $add_time = time();
        $is_delete = 0;
        $collectArray = compact('news_id','uid','add_time' ,'is_delete');
        $collection_id = $this->db->insertRowTable('r_news_collection', $collectArray);

        return $collection_id;
    }
    /**
     * 取消喜欢某帖子
     * @param news_id 帖子id
     * @param uid  用户ID
     * @return
     */
    public function disCollectPost($news_id, $uid)
    {
        $result = 1;
        $is_delete = 1;
        $likeArray = compact('news_id','uid','is_delete');
        if($this->db->updateRowTable('r_news_likes', $likeArray) === false)
        {
            $result = 0;
        }
        return $result;
    }
    
    /**
     * 我喜欢的帖子列表
     * @param int $point 帖子id
     * @return array()
     */
    public function getMyLikePost($uid, $point=0, $direc='next', $offset=20)
    {
        $result = array();

        $userInfo = $_ENV['client']->getUserInfo($uid);
        if($userInfo)
        {
            $redisKey = REDIS_PREFIX.'MyLovePList_'.$uid;
            $limit = array(0, intval($offset));
            if($direc == 'next')
            {
                $posts = $this->redis->ZREVRANGEBYSCORE($redisKey, $point ? $point: '+inf', '-inf', array('limit' => $limit));
            }
            else
            {
                $posts = $this->redis->ZRANGEBYSCORE($redisKey, $point ? $point: '-inf','+inf', array('limit' => $limit));
                krsort($posts);
            }
            if($posts)
            {
                foreach ($posts as $postId) {
                    $postInfo = $this->getPostInfo($postId);
                    if(!empty($postInfo)){
                        $result[] = array('news_id'     => $postInfo['news_id'],
                                          'title'       => $postInfo['title'],
                                          'short_desc'  => $postInfo['short_desc'],
                                          'thumb_img'   => $postInfo['thumb_img'],
                                          'uid'         => $postInfo['uid'],
                                          'authorHeader'  => $this->redis->hget(REDIS_PREFIX.'UserInfo_'.$postInfo['uid'],'header'),
                                          'add_time'    => $postInfo['add_time'],
                                          'loves'       => $postInfo['loves'],
                                          'total_comment'  => $postInfo['total_comment']
                            );
                    }
                    unset($postInfo);
                }
            }
        }
        return $result;
    }
    /**
     * 获取某用户的回复列表
     * @int uid 用户id
     * @int comment_id  界限,一个评论ID
     * @int direc  数据加载方式  next prev
     * @int offset  要获取的评论数量
     * @return array()
     */
    public function getMyCommentPost($uid, $comment_id = 0, $direc = 'next',$offset = 10)
    {
        empty($offset) && $offset = 10;
        $sql = "select c.comment_id, c.news_id, c.comment_content, c.thumb_img, c.thumb_size, c.add_time from r_news_comment as c left join r_news as n on c.news_id = n.news_id where c.uid = {$uid} and c.is_show = 1 and n.is_show = 1";
        if($comment_id > 0)
        {
            $sql .= " and c.comment_id ";
            $sql .= $direc == 'prev' ? "> {$comment_id} order by c.comment_id ASC" : "< {$comment_id} ORDER BY c.comment_id DESC";
        }
        else
        {
            $sql .= ' ORDER BY c.comment_id DESC';
        }
        $sql .= " limit {$offset}";
        $result = $this->db->getall($sql);

        if($result)
        {
            $comment_id > 0 && $direc == 'prev' && rsort($result);
            foreach ($result as & $v)
            {
                $postInfo = $this->getPostInfo($v['news_id']);
                $v['title'] = $postInfo['title'];
                if(!$v['title'])
                {
                    $v['title'] = $this->cutString($postInfo['content'], 200);
                }
            }
        }
        else
        {
            $result = array();
        }
        return $result;
    }
    /**

     * 点亮某帖子评论
     * @int comment_id 评论id
     * @return int  is_success 是否成功
     */
    public function upComment($uid, $comment_id = 0)
    {
        $comInfo = $this->db->getRow("select comment_id, news_id, uid, lights from r_news_comment where comment_id = {$comment_id} and is_show =1");
        if(!empty($comInfo))
        {
            //检查用户是否已点亮过该评论
            if($this->redis->hexists(REDIS_PREFIX.'NewsCommentLight'.$comment_id, $uid))
            {
                $_ENV['error']->getErrors(405);
                exit();
            }
            $is_success = $this->db->query("update r_news_comment set lights = lights +1 where comment_id = {$comment_id}") ? 1 : 0;
            if($is_success)
            {
                $this->redis->hset(REDIS_PREFIX.'NewsCommentLight'.$comment_id, $uid, time());
                $comInfo['lights'] +1 >= $this->base->config['NEWS_HOT_COMMENT_LIMIT'] && $this->updateHotComment($comInfo['news_id']);
                if($uid != $comInfo['uid'])
                {
                    $postInfo = $this->getPostInfo($comInfo['news_id']);
                    $this->addUnReadMsg($comInfo['uid'], array('msgType'=>3, 'sponsor'=>array('uid'=>$uid,'comment_id'=>'0'), 'quote'=>array('news_id'=>$comInfo['news_id'],'comment_id'=>$comment_id)));

                    $this->sendMessage($uid, $comInfo['uid'],$comInfo['news_id'],$comment_id,$postInfo['content'],"N3");
                }
            }
            return $is_success;
        }
        else
        {
            $_ENV['error']->getErrors(101);
            exit();
        }
    }
     /**
     * 隐藏评论
     * @int comment_id 评论id
     * @return int  is_success 是否成功
     */
    public function hidePost($uid, $news_id)
    {
        $result = 0;
        $postInfo = $this->getPostInfo($news_id);
        if(!empty($postInfo))
        {
            if($uid != $postInfo['uid'])
            {
                $_ENV['error']->getErrors(103);
                exit;
            }
            if($this->update(array('news_id' => $news_id,  'is_show' => 0)))
            {
                $this->base->result['result']['is_success'] = 1;
                $this->base->breakCall();
                $this->redis->hset(REDIS_PREFIX.'NewsInfo_'.$news_id, 'is_show' , 0);
                $board = $postInfo['board'];
                $tag = $postInfo['tag'];
                if(is_array($board) && !empty($board))
                {
                    foreach ($board as $v) {
                        foreach (common::$postListType as $type) {
                            $this->redis->zrem(REDIS_PREFIX.'BoardPostList'.$v['boardId'].'_'.$type, $news_id);
                        }
                        //24小时内文章
                        if($v=='showtime'){
                            $this->redis->zrem(REDIS_PREFIX.'BoardPostList'.$v.'_New24H',$news_id);
                            //同城
                            $city = $this->base->load('ip')->find(common::getip());
                            $city = md5($city[2]);
                            $this->redis->zrem(REDIS_PREFIX.'BoardPostList'.$v.'_Locale_'.$city,$news_id);
                        }
                    }
                }
                if(is_array($tag) && !empty($tag))
                {
                    foreach ($tag as $v) {
                        foreach (common::$postListType as $type) {
                            $this->redis->zrem(REDIS_PREFIX.'TagPostList'.$v['tagId'].'_'.$type, $news_id);
                        }
                    }
                }
            }
        }
        return $result;
    }
    /**
     * 隐藏帖子
     * @int comment_id 评论id
     * @return int  is_success 是否成功
     */
    public function hideComment($uid, $comment_id)
    {
        $result = 0;
        $commentInfo = $this->db->getRow("select news_id, lights, is_show from r_news_comment where uid = '{$uid}' and comment_id = '{$comment_id}' limit 1");
        if(!empty($commentInfo) && $commentInfo['is_show'] == 1)
        {
            if($this->db->update("update r_news_comment set is_show = '0' where comment_id = '{$comment_id}'"))
            {
                $this->base->result['result']['is_success'] = 1;
                $this->base->breakCall();
                $news_id = $commentInfo['news_id'];
                $commentInfo['lights']-1 > $this->base->config['NEWS_HOT_COMMENT_LIMIT'] && $this->updateHotComment($news_id);
                $this->redis->HINCRBY(REDIS_PREFIX. 'NewsInfo_'.$news_id, 'total_comment', -1);
                $this->db->update("update r_news set total_comment = total_comment-1 where news_id = '{$news_id}'");
                //$this->update(['total_comment'=>'?-1','news_id'=>$news_id]);
            }
        }
        return $result;
    }
    /*
     * 添加社区未读消息
     * int uid 用户id
     * array()  $data array('msgId','msgType', 'sponsor'=>array('uid','comment_id'), 'quote'=>array('news_id','comment_id'))
    */
    public function addUnReadMsg($uid, $data = array())
    {
        $result = false;
        $redisKey = REDIS_PREFIX.'unReadBbsMsg_'.$uid;
        extract($data);
        if(isset(common::$bbsMsgType[$msgType]) && !empty($sponsor) && !empty($quote))
        {
            $insertData = array('uid'   => $uid,
                                'msgType'   => $data['msgType'],
                                'sponsor'   => json_encode($sponsor),
                                'quote'     => json_encode($quote),
                                );
            $msgId = $this->db->insertRowTable('r_msg', $insertData);
            $sponsor['header'] = $this->redis->hget(REDIS_PREFIX.'UserInfo_'.$sponsor['uid'], 'header');
            $sponsor['nickname'] = $this->redis->hget(REDIS_PREFIX.'UserInfo_'.$sponsor['uid'], 'nickname');
            $sponsor['content'] = '';
            if(in_array($msgType, array(1,4,5)))
            {
                $quote['content'] = $this->redis->hget(REDIS_PREFIX.'NewsInfo_'.$quote['news_id'], 'title');
            }
            else if(in_array($msgType, array(2,3)))
            {
                $quote['content'] = $this->db->getOne("select comment_content from r_news_comment where news_id = '".$quote['news_id']."' and comment_id = '".$quote['comment_id']."'");
            }
            if(in_array($msgType, array(1,2)))
            {
                $sponsor['content'] = $this->db->getOne("select comment_content from r_news_comment where comment_id = '".$sponsor['comment_id']."'");
            }
            $redisData = compact('msgId','msgType','sponsor','quote');
            $this->redis->ZADD($redisKey, time(), json_encode($redisData));
            $result = true;

            
        }
        return $result;
    }
    /*
     * 获取社区未读消息列表
     * boolen $onlyNum  是否只返回总数
    */
    public function getunReadMsg($uid, $onlyNum = false)
    {
        $redisKey = REDIS_PREFIX.'unReadBbsMsg_'.$uid;
        if($onlyNum)
        {
            return $this->redis->ZCARD($redisKey);
        }
        $result = array();
        $data = $this->redis->ZREVRANGEBYSCORE($redisKey, '+inf', '-inf');
        if($data)
        {
            foreach ($data as & $value) {
                $value = json_decode($value, true);
                if(!empty($value))
                {
                    unset($value['sponsor']['uid']);
                    $result[] = $value;
                    $value = array();
                }
            }
        }
        return $result;
    }
    /**
     * 验证版块ID
     * @return int/array() $board
     */
    public function checkBoard($board)
    {
        if(is_array($board))
        {
            $boardIds = array();
            foreach ($board as $v) {
                if($this->checkBoard($v))
                {
                    $boardIds[] = $v;
                }
            }
            return $boardIds;
        }
        else
        {
            if($this->redis->ZSCORE(REDIS_PREFIX.'BoardList', $board) !== false)
            {
                return $board;
            }
            return '';
        }
    }
    /**
     * 验证标签
     * @return json $tag
     */
    public function checkTag($tag)
    {
        $result = array();
        if(is_array($tag) && !empty($tag))
        {
            foreach ($tag as $tagId) {
                if($this->redis->exists(REDIS_PREFIX.'TagInfo_'.$tagId))
                {
                    $result[] = $tagId;
                }
            }
        }
        return json_encode($result);
    }
    /**
     * 更新社区首页热门帖子
     * int $duration  需要计算回复数的时间周期 (默认3天)
     * int $num  列表长度
     * @return
     */
    public function updateTopHotPost($days = 30, $num = 20)
    {
        $redisKey = REDIS_PREFIX.'TopHotpost';
        $this->redis->del($redisKey);

        $duration = 86400 * $days;
        $deadLine = time() - $duration;
        $extractSql = '';

        $ignorePost = $this->getTopHotIgnore();
        if($ignorePost)
        {
            $db_create_in = $this->base->load('push')->db_create_in($ignorePost);
            $extractSql = ' and news_id not '.$db_create_in;
        }

        // $posts = $this->db->getAll("select news_id, total_comment from r_news where is_show = 1".$extractSql." and total_comment > 2 and a_channel = '' and add_time > '{$deadLine}' and board != '[\"0\"]' order by total_comment DESC limit $num");
        $posts = $this->db->getAll("select news_id, total_comment from r_news where is_show = 1".$extractSql." and total_comment > 2 and a_channel = '' and add_time > '{$deadLine}' and board != '[\"0\"]' order by total_comment DESC");
        if(!empty($posts))
        {
            $list = array();
            foreach ($posts as $v) {
                $list[$v['news_id']] = $v['total_comment'];
            }
            arsort($list);
            foreach ($list as $key => $value)
            {
                $time = $this->db->getOne("select add_time from r_news_comment where news_id = '{$key}' and is_show=1 order by add_time DESC limit 1");
                $time = intval($time);
                $this->redis->ZADD($redisKey, $time, $key);
            }
        }
        //common::pr($list);
        return;
    }
    /**
     * 获取社区首页热门中被屏蔽的帖子
     * @return array 
     */
    public function getTopHotIgnore()
    {
        $redisKey = REDIS_PREFIX.'TopHotIGPost';
        $result = $this->redis->SMEMBERS($redisKey);

        empty($result) && $result = array();

        return $result;
    }
    /*
     * 社区首页推荐帖子列表(2.5.0)
     * @param news_id 帖子id
     * @param direc 数据追加方式
     * @param offset 数据条数
     * @return $array
    */
    public function getHomeBestPostList($news_id = 0, $direc = 'next', $offset = '20')
    {
        $redisKey = REDIS_PREFIX.'BbsBestPost';
  
        // 如果无缓存，生成缓存
        if($this->redis->exists($redisKey) == false)
        {
            $this->updateHomeBestPost();
        }

        if($news_id > 0 )
        {
            if($direc == 'next')
            {
                $start = $this->redis->ZREVRANK($redisKey, $news_id);
                $top = $start + $offset;
                $start += 1;
                $postList = $this->redis->ZREVRANGE($redisKey, $start, $top);
            }
            else
            {
                $start = $this->redis->ZRANK($redisKey, $news_id);
                $top = $start + $offset;
                $start += 1;
                $postList = $this->redis->ZRANGE($redisKey, $start, $top);

                !empty($postList) && krsort($postList);
            }
        }
        else
        {

            $postList = $this->redis->ZREVRANGE($redisKey, 0, $offset-1);

        }
        return $postList;
    }
    /**
     * 更新社区首页推荐帖子(2.5.0)
     * int $duration  需要计算回复数的时间周期 (默认3天)
     * int $num  列表长度
     * @return
     */                          
    public function updateHomeBestPost($days = 3, $limit = 100)
    {
        $redisKey = REDIS_PREFIX.'BbsBestPost';

        // 计算发帖截止时间
        $days = intval($days);
        $deadLine = time() - 86400 * $days;

        // 获取被屏蔽的帖子
        $extractSql = '';
        $ignorePost = $this->getHomeBestPostIgnore();
        if($ignorePost)
        {
            $db_create_in = $this->base->load('push')->db_create_in($ignorePost);
            $extractSql = ' and news_id not '.$db_create_in;
        }

        // 获取帖子列表
        $posts = $this->db->getAll("select news_id, total_comment, loves, add_time from r_news where is_show = 1".$extractSql." and a_channel = '' and add_time > '{$deadLine}' and board != '[\"0\"]' and board !='[\"groupNews\"]' order by total_comment DESC");
        if(!empty($posts))
        {           
            $list = $this->_recommend($posts);
            // 删除原缓存数据
            $this->redis->del($redisKey);

            // 生成缓存
            $n = 0;
            foreach ($list as $news_id => $score)
            {
                if($n < $limit)
                {
                    $this->redis->ZADD($redisKey, $score, $news_id);
                    $n++;
                }
            }
        }
        return ;
    }
     /**
     * 获取社区首页热门中被屏蔽的帖子(2.5.0)
     * @return array 
     */
    public function getHomeBestPostIgnore()
    {
        $redisKey = REDIS_PREFIX.'BbsBestIGPost';
        $result = $this->redis->SMEMBERS($redisKey);

        empty($result) && $result = array();

        return $result;
    }

    /**
     * 获取帖子类型
     * @param int $postId 
     * @return 
     */
    public function getPostType($postId)
    {
        
        return 1;
    }
    /**
     * 根据原图获取中图
     * @return array 
     */
    public function getPostMidImg(array $source_img, $width = 720, $height = 720)
    {
        $middle_img = array();

        // 图片域名部分
        $imgHost = $this->base->load('qiniu')->getQNHost();

        foreach ($source_img as $key => $v)
        {
            // if(!$v || stripos($v, $imgHost) === false)
            if(!$v)
            {
                $middle_img[$key] = $v;
            }
            else
            {
                $middle_img[$key] = $v .'?imageView2/2/w/'. $width .'/h/'.$height . '/format/jpg/q/70';
            }
        }
        
        return $middle_img;
    }
    /**
     * 获取版块附加模块
     * @param string boardId
     * @return array 
     */
    public function getBoardAdditions($boardId = '')
    {
        if(!$boardId)
        {
            return array();
        }

        $result = $this->db->getAll("select name, description, img, link from r_board_addition where board = '{$boardId}' and is_show = 1");

        return $result;
    }
 
    /**
     * 帖子搜索
     * @param string $keywords  搜索关键词
     * @param string $boardId  版块id
     * @param int $news_id  帖子id
     * @param string  $direc 数据追加方式
     * @param int  $offset
     * @return array 
     */
    public function search($keywords, $boardId = '', $news_id = 0, $direc = 'next', $offset = 10)
    {
        $result = array();
        $redisKey = REDIS_PREFIX.'BS_'.urlencode($keywords).'_'.$boardId;
        
        if($this->redis->exists($redisKey) == false)
        {

            $res = $this->base->load('xunSearch')->init('news')->getSearcher()->setMultiSort(['news_id'=>false,'total_comment'=>false])->setLimit(100)
                    ->search("board:$boardId is_show:1 news_id:$keywords OR $keywords");
            $postIds = [];
            foreach($res as $v){
                $postIds[] = $v->news_id;
            }
            /*
            $keywords = common::mysql_real_escape_string($keywords);
            $sql = "select news_id from r_news where is_show = 1 and title like '%{$keywords}%'";
            $boardId && $sql .= " and board like '%{$boardId}%'";
            $sql .= ' order by total_comment ASC';
            
            $postIds = $this->db->getCol($sql);
            */
            
            if(!empty($postIds))
            {
                foreach ($postIds as $key => $v)
                {
                    $this->redis->ZADD($redisKey, $key, $v);
                }

                $this->redis->EXPIRE($redisKey, 1800);
            }
        }

        // 获取数据
        if($this->redis->exists($redisKey) !== false)
        {
            $point = 0;
            if($news_id > 0)
            {
                $point = $direc == 'next' ? $this->redis->ZREVRANK($redisKey, $news_id) : $this->redis->ZRANK($redisKey, $news_id);
                $point !== false && $point += 1;
            }
            $limit = array(intval($point), intval($offset));
            if($direc == 'next')
            {
                $result = $this->redis->ZREVRANGEBYSCORE($redisKey, '+inf', '-inf', array('limit' => $limit));
            }
            else
            {
                $result = $this->redis->ZRANGEBYSCORE($redisKey, '-inf', '+inf', array('limit' => $limit));
            }
        }

        return $result;
    }
    
    /*
     * 搜索时推荐的帖子，高亮关键词
     * @param string $keywords  搜索关键词
     * @param string $boardId  版块id
     * @return array 
     */
    public function searchRec($keywords,$boardId = '',$limit=10){
        $searcher = $this->base->load('xunSearch')->init('news')->getSearcher();
        $res = $searcher->setLimit($limit,0)->search("board:$boardId is_show:1 title:$keywords");
        $docs = [];
        foreach($res as $v){
            $docs[] = [
                'news_id' => $v->news_id,
                'title' => $searcher->highlight($v->title)
            ];
        }
        return $docs;
    }
    
    /**
     * 推荐热度计算  评论数+喜欢数+时间权重
     * @access private
     * @param  array $reData
     * @return array
     */
    private function _recommend(array $reData)
    {
        if( !empty( $reData ) )
        {
            //时间热度映射表
            $hotVal = array( 'hour12' => 30, 'hour24' => 20);
            $posts = array();
            foreach( $reData as $info )
            {
                $time = time() - $info['add_time'];
                $score = $info['total_comment'] + $info['loves'];
                //当基数大于5时对热度值进行调整
                if($score > 5){
                    if(  $time > 0 && $time <= 12*3600 )
                    {
                        $score += $hotVal['hour12'];
                    }
                    elseif( $time > 12*3600 && $time <= 24*3600 )
                    {
                        $score += $hotVal['hour24'];
                    }
                }
                
                $posts[$info['news_id']] = $score;
            }
            return $posts;
        }
        return $reData;
        
    }

    /**
     * 获取showtime图片集
     * @param bool $flag
     * @param int $offset
     * @param int $end
     * @return array
     */
    public function getPosition($flag=true,$offset=0,$end=-1)
    {
        $data = $this->redis->ZREVRANGE(REDIS_PREFIX.'bbsADPosition',$offset,$end);
        $result = array();
        if(!empty($data)){
            $count = count($data);
            for($i=0;$i<$count;$i++){
                $info = json_decode($data[$i],true);
                $result[$i]['pictureUrl'] = $info['pictureUrl'];
                $result[$i]['linkUrl'] = $info['linkUrl'];
                $flag===true && $result[$i]['sort'] = $this->redis->zscore(REDIS_PREFIX.'bbsADPosition',$data[$i]);
            }
        }
        return $result;
    }
    
    public function insert($data)
    {
        $news_id = $this->db->insertRowTable('r_news', $data);
        if($data['title'] && $news_id){
            $data['title'] = str_replace('#','刱',$data['title']);
            $data['content'] = str_replace('#','刱',strip_tags($data['content']));
            $this->base->load('xunSearch')->init('news')
                ->addIndex(['news_id'=>$news_id,'title'=>$data['title'],'content'=>$data['content'],'board'=>$data['board'],'is_show'=>$data['is_show'],'total_comment'=>$data['total_comment']]);
        }
        return $news_id;
    }
    
    public function update($data)
    {
        $res = $this->db->updateRowTable('r_news', $data);
        $fields = ['title','content','board','is_show','total_comment'];
        if(array_intersect_key($data,array_flip($fields)) && $res){
            $row = $this->db->getRowTable('r_news',$fields,"news_id='{$data['news_id']}'");
            $row['news_id'] = $data['news_id'];
            $row['title'] = str_replace('#','刱',$row['title']);
            $row['content'] = str_replace('#','刱',strip_tags($row['content']));
            $this->base->load('xunSearch')->init('news') ->updateIndex($row);
        }
        return $res;
    }

    /*
     * 获得有道导航
     */
    public function getBbsChannel(){
        $data = $this->redis->GET(REDIS_PREFIX.'bbsChannel');
        return json_decode($data,true);
    }
    
    /*
     * 首页两个图片展示位
     */
    public function getGearNewsBanner(){
        return $this->base->load('banner')->getGearNewsBanner();
    }
    
    /*
     * 获得随机问答
     */
    public function getRandAns($limit=1,$since_id=0){
        /*
        $boardIds = ['healthy', 'injury', 'beginner', 'training'];
        $key = array_rand($boardIds,1);
        $redisKey = REDIS_PREFIX.'BoardPostList'.$boardIds[$key].'_New';
        $count = $this->redis->zcard($redisKey);
        $start = rand(0,$count-20-$limit);
        $stop = $count - $start;
        
        $ans = $this->redis->zrange($redisKey,$start,$stop);
        
        if(empty($ans)){
            return [];
        }else{
            $count = count($ans);
            $limit = $limit > $count ? $count : $limit;
            shuffle($ans);
            return array_slice($ans,0,$limit);
        }
        */
        
        $redisKey = REDIS_PREFIX.'PuniuPostList';
        return $this->redis->srandmember($redisKey,$limit);
    }
    
    /*
     * 获取最新装备类资讯
     * 默认倒序
     */
    public function getGearNews($limit=1){
        $news1 = $this->redis->zrange(REDIS_PREFIX.'BoardPostListgearEval_New',-$limit,-1);
        $news2 = $this->redis->zrange(REDIS_PREFIX.'BoardPostListrungear_New',-$limit,-1);
        $news3 = $this->redis->zrange(REDIS_PREFIX.'BoardPostListgearNews_New',-$limit,-1);
        $arr = array_unique(array_merge($news1,$news2,$news3));
        rsort($arr);
        return array_slice($arr,0,$limit);
    }
    
    /*
     * 添加草稿
     */
    public function addDraft($args){
        return $this->db->insertRowTable('r_news_draft',$args);
    }
    
    /*
     * 临时存放图片
     */
    public function insertTempImg($url){
        $this->base->db->insertRowTable('r_temp_image',['url'=>$url,'addtime'=>time()]);
    }
    
    /*
     * 删除无用的临时图片
     */
    public function clearTempImg($urls){
        if(empty($urls)){
            return;
        }
        $time = time()-48*24*3600-1800;//两天前，和pc提交文章最长时间相同
        $urls_str = "'".implode("','",$urls)."'";
        $where = "addtime<$time";
        $rows = $this->base->db->getAll('select url from r_temp_image where'.$where." AND url NOT IN ($urls_str)");
        if(empty($rows)){
            return;
        }
        
        $qiniu_mod = $this->base->load('qiniu');
        $qiniu_mod->batchDeleteImg($rows);
        $this->base->db->delDataTable('r_temp_image',$where);
    }
    
    /*
     * 获得用户帖子
     */
    public function getUserPostList($boardId, $news_uid, $news_id, $direc='next', $limit=10){
        if($news_uid == $this->base->uid){
            $redisKey = REDIS_PREFIX.'UserPostList_My'.$news_uid;
            $sql = "select r_news.news_id,r_news.add_time from r_news where uid={$news_uid} AND is_show=1";
        }else{
            $redisKey = REDIS_PREFIX.'UserPostList_Other'.$news_uid;
            $sql = "select r_news.news_id,r_news.add_time from r_news left join r_boardpost on r_boardpost.news_id = r_news.news_id where r_boardpost.boardId IN('showtime','groupNews','hotans') AND uid={$news_uid} AND is_show=1";
        }
        
        if(!$this->redis->exists($redisKey)){
            $res = $this->db->getAll($sql);
            if(empty($res)){
                return [];
            }
            foreach($res as $row){
                $this->redis->zadd($redisKey,$row['add_time'],$row['news_id']);
            }
            $this->redis->expire($redisKey, 60);
        }
        
        if(!$news_id){
            $postList = $this->redis->zrevrange($redisKey, 0 ,$limit-1);
        }else{
            $start = $this->redis->ZREVRANK($redisKey, $news_id) + 1;
            $top = $start + $limit;
            $postList = $this->redis->ZREVRANGE($redisKey, $start, $top);
        }
        
        return $postList;
    }
    
    /*
     * 检测文章里的"@"
     */
    public function filterAt($string){
        preg_match_all('/<at href="joggers:\/\/profile\/(\d*?)">(.+?)<\/at>/',$string,$matches);
        if(empty($matches)){
            return ['string'=>$string,'uids'=>[]];
        }
        $user_mod = $this->base->load('user');
        $uids = [];
        $_matches = $matches[0];
        $_uids = $matches[1];
        $_nicknames = $matches[2];
        foreach($_matches as $key=>$match){
            //搜索未知用户
            if(!$_uids[$key]){
                $nickname = trim($_nicknames[$key]);
                $uid = $user_mod->getUidByNickname($nickname);
                if(!$uid){
                    continue;
                }
                $string = str_replace($match,"<at href=\"joggers://profile/{$uid}\">$nickname</at>",$string);
            }
            $uids[] = isset($uid) ? $uid : $_uids[$key];
        }
        return compact('string','uids');
    }
    
    /*
     * 转换@标签
     */
    public function buildPostAt($string){
        preg_match_all('/<at href="(.*?)">(.+?)<\/at>/',$string,$matches);
        $_matches = $matches[0];
        $_schemes = $matches[1];
        $_nicknames = $matches[2];
        foreach($_matches as $key=>$match){
            $scheme = $_schemes[$key];
            $nickname = $_nicknames[$key];
            $string = str_replace($match,"<a class=\"topic\" href=\"{$scheme}\">@{$nickname}</a>",$string);
        }
        return $string;
    }

    /*
     * 查询用户投诉信息
     */
    public function getComplaints($news_id, $uid, $reason){
        $sql = "select * from r_complaints where status = 0 and news_id={$news_id} and uid={$uid} and reason='{$reason}'";
        $ComplaintsInfo = $this->db->getAll($sql);
        return $ComplaintsInfo;
    }

    /*
     * 新增用户投诉
     */
    public function addComplaints($params){
        $c_id = $this->db->insertRowTable('r_complaints', $params);
        return $c_id;
    }

    /*
     * 查询投诉数量信息
     */
    public function getComplaintsCount($news_id, $reason = 0){
        $sql = "select * from r_complaints_count where news_id={$news_id}";
        if($reason)
        {
            $sql .= " and reason='{$reason}'";
        }
        $countInfo = $this->db->getAll($sql);
        return $countInfo;
    }

    /*
     * 新增帖子投诉数量
     */
    public function addComplaintsCount($countParams){
        $cid = $this->db->insertRowTable('r_complaints_count', $countParams);
        return $cid;
    }

    /*
     * 更新帖子投诉数量
     */
    public function updateComplaintsCount($news_id){
        $cid = $this->db->update("update r_complaints_count set count = count+1 where news_id = {$news_id}");
        return $c_id;
    }
}
?>